<?php

class oFile extends oClass implements oInterfaceReader, oInterfaceWriter
{
    protected $addr     = null;
    protected $mode     = null;
    protected $h        = null;

    public function __construct($addr)
    {
        $this->addr = $addr;
    }

    public function exists()
    {
        return file_exists($this->addr);
    }

    public function Opened()
    {
        return $this->h !== null;
    }

    public function open($mode)
    {
        $this->h = fopen($this->addr, $mode);
        $this->mode = $mode;
        return $this->Opened();
    }

    public function CanRead()
    {
        return $this->Opened() && $this->mode = 'r';
    }

    protected function CheckRead()
    {
        if (!$this->CanRead())
        {
            throw new eNotReadable();
        }
    }

    public function CanWrite()
    {
        return $this->Opened() && in_array($this->mode, array('a', 'w'));
    }

    protected function CheckWrite()
    {
        if (!$this->CanWrite())
        {
            throw new eNotWritable();
        }
    }

    public function Read($count = 1)
    {
        $this->CheckRead();
        return fread($this->h, 1);
    }

    public function ReadTo($limiter)
    {
        $this->CheckRead();
        $return = '';
        $al     = '';
        while($char = fread($this->h, 1))
        {
            $al .= $char;
            if (strpos($limiter, $al) !== 0)
            {
                $return .= $al;
                $al = '';
                continue;
            }
            if ($al == $limiter) return $return;
        }
        return null;
    }

    function ReadAll()
    {
        return file_get_contents($this->addr);
    }

    public function WriteLn($data)
    {
        return $this->write($data."\n");
    }

    public function Write($data)
    {
        $this->CheckWrite();
        fwrite($this->h, $data);
        return true;
    }

    public function Unlink()
    {
        if (!$this->exists()) return false;
        $this->Close();
        return unlink($this->addr);
    }

    public function Close()
    {
        if ($this->Opened())
        {
            fclose($this->h);
        }
        return true;
    }

    public function  __destruct()
    {
        $this->Close();
    }

}

?>